<template>
  <view class="assist_wrapper">
    <view class="header_wrapper">
      <image src="/static/user/logo.png" />
      <text>易联小铺</text>
    </view>
    <view class="info_wrapper">
      <u-form :model="formData" ref="uForm" label-width="200">
        <u-form-item label="手机号码" prop="phone">
          <u-input v-model="formData.phone" placeholder="请输入手机号码" />
        </u-form-item>
        <u-form-item
          label="验证码"
          prop="verificationCode"
          class="code_wrapper"
        >
          <view class="code_info">
            <u-input
              v-model="formData.verificationCode"
              placeholder="请输入验证码"
            />
            <view class="code_">
              <u-toast ref="uToast"></u-toast>
              <u-verification-code
                :seconds="seconds"
                @end="end"
                @start="start"
                :change-text="'已发送(xS)'"
                ref="uCode"
                @change="codeChange"
              ></u-verification-code>
              <view @tap="getCode" class="text_">{{ tips }}</view>
            </view>
          </view>
        </u-form-item>
      </u-form>
    </view>
    <view class="footer_wrapper">
      <view @tap="submit">登录</view>
    </view>
  </view>
</template>

<script>
import { sendSmsCode, switchAccount } from "../../../api/assist/index.vue";

const app = getApp();
export default {
  name: "index.vue",
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  data() {
    return {
      tips: "",
      seconds: 60,
      formData: {
        phone: "",
        verificationCode: "",
        code: "",
      },
      rules: {
        phone: [
          {
            required: true,
            message: "请输入手机号",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              console.log(value, "手机号");
              if (value == "") {
                return callback("请输入手机号");
              } else {
                // 上面有说，返回true表示校验通过，返回false表示不通过
                // this.$u.test.mobile()就是返回true或者false的
                return this.$u.test.mobile(value);
              }
            },
            message: "手机号码不正确",
            // 触发器可以同时用blur和change
            trigger: ["blur"],
          },
        ],
        verificationCode: [
          {
            required: true,
            message: "请输入验证码",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  methods: {
    end() {
      // this.$u.toast("倒计时结束");
    },
    start() {
      // this.$u.toast("倒计时开始");
    },
    //倒计时期间，每秒触发一次
    codeChange(text) {
      // console.log(text, "倒计时");
      this.tips = text;
    },

    async getCode() {
      if (this.formData.phone) {
        if (this.$refs.uCode.canGetCode) {
          // 模拟向后端请求验证码
          uni.showLoading({
            title: "正在获取验证码",
          });
          const res = await sendSmsCode(this.formData.phone);
          console.log(res, "验证码");
          if (res.code === 0) {
            uni.hideLoading();
            // 这里此提示会被this.start()方法中的提示覆盖
            this.$u.toast("验证码已发送");
            // 通知验证码组件内部开始倒计时
            this.$refs.uCode.start();
          }
        } else {
          this.$u.toast("倒计时结束后再发送");
        }
      } else {
        uni.showToast({
          title: "请输入手机号",
          icon: "error",
          duration: 2000,
        });
      }
    },

    submit() {
		console.log("ddel")
      this.$refs.uForm.validate(async (valid) => {
        if (valid) {
          const code = await app.globalData.getCode();
          console.log(code, "code");
          this.formData.code = code;
          console.log("验证通过");
          const res = await switchAccount(this.formData);
          console.log(res, "切换账号");
          if (res.code === 0) {
            uni.showToast({
              title: "登录成功",
              icon: "success",
              duration: 2000,
            });
            // 获取到的当前数据存入缓存
            const { wxToken, openId, userInfo } = res.data;
            uni.setStorageSync("token", wxToken);
            uni.setStorageSync("openId", userInfo.wxOpenid);
            uni.setStorageSync("userInfoServer", userInfo);
            uni.setStorageSync("phoneNumber", userInfo.phone);
            uni.setStorageSync("userId", userInfo.userId);
            setTimeout(() => {
              // 跳转回原页面
              uni.navigateBack({
                delta: 1,
              });
            }, 1500);
          } else {
            uni.showToast({
              title: "登录失败",
              icon: "success",
              duration: 2000,
            });
          }
        } else {
          console.log("验证失败");
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.code_wrapper {
  display: flex !important;
  ::v-deep .code_info {
    flex: 1;
    display: flex;
    align-items: center;

    u-input {
      flex: 1;
      .u-input__input {
        padding-right: rpx(10);
      }
    }
    .code_ {
      width: rpx(84);
      height: rpx(30);
      background: #10aeff;
      border-radius: rpx(5);
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: rpx(10);
      > .text_ {
        font-size: rpx(13);
        font-weight: 400;
        color: #ffffff;
      }
    }
  }
}

.assist_wrapper {
  background: #ffffff;
  height: 100vh;
  > .header_wrapper {
    display: flex;
    flex-direction: column;
    padding: rpx(48) rpx(0);
    justify-content: center;
    align-items: center;
    > image {
      width: rpx(64);
      height: rpx(64);
      vertical-align: middle;
      margin-bottom: rpx(8);
    }
    > text {
      font-size: rpx(14);
      font-weight: 400;
      color: #353535;
    }
  }
  > .info_wrapper {
    padding: rpx(0) rpx(12);
  }
}

.footer_wrapper {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: rpx(8) rpx(12) rpx(25);
  > view {
    display: flex;
    align-items: center;
    justify-content: center;
    width: rpx(351);
    height: rpx(44);
    background: #fa5151;
    border-radius: rpx(22);
    font-size: rpx(17);
    font-weight: 400;
    color: #ffffff;
  }
}
</style>
